package err_group

import (
	"context"
	"errors"
	"fmt"
	"golang.org/x/sync/errgroup"
	"log"
	"time"
)

func NoRt() {
	g, ctx := errgroup.WithContext(context.Background())

	// 启动多个 goroutine
	g.Go(func() error {
		time.Sleep(100 * time.Millisecond)
		fmt.Println("Task 1 completed")
		return nil
	})

	g.Go(func() error {
		time.Sleep(200 * time.Millisecond)
		fmt.Println("Task 2 completed")
		return nil
	})

	g.Go(func() error {
		time.Sleep(150 * time.Millisecond)
		fmt.Println("Task 3 completed")
		return nil
	})

	// 等待所有任务完成
	if err := g.Wait(); err != nil {
		log.Fatal("Error:", err)
	}
	fmt.Println("All tasks completed successfully")

	// 检查上下文是否被取消
	select {
	case <-ctx.Done():
		fmt.Println("Context was cancelled")
	default:
		fmt.Println("Context is still active")
	}
}

func ErrorRt() {
	g, ctx := errgroup.WithContext(context.Background())

	g.Go(func() error {
		time.Sleep(100 * time.Millisecond)
		fmt.Println("Task 1: Success")
		return nil
	})

	g.Go(func() error {
		time.Sleep(50 * time.Millisecond)
		fmt.Println("Task 2: Failed")
		return errors.New("task 2 failed")
	})

	g.Go(func() error {
		// 这个任务会检测到上下文取消
		select {
		case <-ctx.Done():
			fmt.Println("Task 3: Cancelled due to error in other task")
			return ctx.Err()
		case <-time.After(200 * time.Millisecond):
			fmt.Println("Task 3: Completed (this shouldn't happen)")
			return nil
		}
	})

	// 返回第一个错误
	if err := g.Wait(); err != nil {
		fmt.Printf("One of the tasks failed: %v\n", err)
	}
	fmt.Println("------over-----------")
}

func RunWithAnts() {

}
